import os

from restfx import route

from misc import Result, load_list, Info, get_id
from worker import do_test_all, test_one


@route()
def get():
    try:
        return Result.ok(load_list(True))
    except Exception as ex:
        return Result.bad(str(ex))


@route()
def post(name, ip, port):
    fileid = get_id(ip, port)
    info = Info.load(fileid)
        
    if info is None:
        info = Info()

    info.id = fileid
    info.name = name
    info.ip = ip
    info.port = port

    info.dump()

    test_one(info)

    return Result.ok(None)


@route()
def post_refresh(ip, port):
    fileid = get_id(ip, port)
    info = Info.load(fileid)
    if info:
        info.refresh()
        return Result.ok(None)
    else:
        return Result.bad('Item not exist')


@route()
def post_refresh_all():
    do_test_all()
    return Result.ok(None)


@route()
def delete(ip, port):
    fileid = get_id(ip, port)
    info = Info.load(fileid)
    if info:
        info.delete()
        return Result.ok(None)
    else:
        return Result.bad('%s:%s does not exist' % (ip, port))
